package com.atguigu.zk.distributedlock;

import org.apache.zookeeper.KeeperException;

import java.io.IOException;

/**
 * 手动实现分布式锁，案例测试
 * 两个异步同时运行的线程，观察锁的争抢情况
 */
public class DistributedLockTest {
    public static void main(String[] args) throws InterruptedException, IOException, KeeperException {
        DistributedLock lock1 = new DistributedLock();
        DistributedLock lock2 = new DistributedLock();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    lock1.addLock();
                    System.out.println("---线程1 启动，向zk中注册锁信息，并获取锁");
                    Thread.sleep(5*1000);
                    lock1.removeLock();
                    System.out.println("---线程1 释放锁，并删除锁信息");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    lock2.addLock();
                    System.out.println("---线程2 启动，向zk中注册锁信息，并获取锁");
                    Thread.sleep(5*1000);
                    lock2.removeLock();
                    System.out.println("---线程2 释放锁，并删除锁信息");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();


    }
}
